from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
import random,redis,jwt,datetime,time
from .tasks import send_sms
from myapp.models import *
from django.conf import settings
from .serializer import *
from decorator.decorator import check_login,merchant_login
from rest_framework.viewsets import ModelViewSet
from werkzeug.security import generate_password_hash,check_password_hash
from qiniu import Auth
# Create your views here.


# 发送验证码
class SmsAPIView(APIView):
    def post(self, request):

        # 获取前端数据
        mobile = request.data.get('mobile')
        print("获取到的手机号>>>", mobile)
        # 数据校验
        if not all([mobile,]):
            return Response({
                "code": 400,
                "msg": "数据不完整"
            })
        # 生成验证码
        sms_code = "%d"%random.randint(10000,99999)

        print('验证码:', sms_code)
        # 存入redis
        redis_coon = redis.Redis(host='localhost', port=6379, password='123', db=3)
        redis_coon.set("sms_%s"%mobile,sms_code,ex=300)
        rds = redis_coon.get("sms_%s"%mobile)
        # print('red', rds)

        # 请求容联云发送短信验证码
        res = send_sms.delay(sms_code,mobile)

        return Response({
            'code':200,
            'msg':'短信验证码发送成功！',
        })


# 商家登录
class MerchantAPIView(APIView):
    def post(self, request):
        username = request.data.get('username')
        pwd = request.data.get("pwd")
        mobile = request.data.get("mobile")
        sms_code = request.data.get("sms_code")

        try:
            user = Merchant.objects.filter(username=username).first()
            if not user:
                return Response({
                    "code": 400,
                    "msg": "没有此用户"
                })

            code_key = "sms_" + mobile

            redis_conn = redis.Redis(host='localhost', port=6379, password='123', db=3)
            # 验证验证码
            sms = redis_conn.get(code_key)
            if not sms:
                return Response({
                    'code':204,
                    'msg': "验证码过期"
                })
            if sms.decode() != sms_code:
                return Response({
                    "code": 204,
                    'msg': "验证码错误"
                })

            pwdd = Merchant.objects.filter(pwd=pwd).first()

            if pwdd:
                token = self.gen_token(user)
                user.last_login = datetime.datetime.now()
                user.save()

                return Response({
                    'code': 200,
                    'msg': "登录成功",
                    'username': user.username,
                    'id': user.id,
                    'token': token
                })
            else:
                return Response({
                    'code': 204,
                    'msg': "密码错误"
                })
        except Exception as e:
            print('错误', e)
            return Response({
                "code": 500,
                "msg": "服务器出错误了哦！"
            })
    @staticmethod
    def gen_token(user):
        # 组织payload数据
        payload = {
            'id':user.id,
            'exp': time.time() + 30000000
        }

        # 使用jwt编码，生成token
        token = jwt.encode(payload=payload, key=settings.SECRET_KEY,algorithm='HS256')
        return token


# 商家的管理
class MerchantViewSet(ModelViewSet):
    queryset = Merchant.objects.all()
    serializer_class = MerchantSer
    @merchant_login
    def list(self, request, *args, **kwargs):
        # 查询已登录的用户
        user_id = request.user

        print('meid', user_id)
        mechant = Merchant.objects.filter(username=user_id).first()
        data = {
            "code": 200,
            "msg": "ok",
            "userinfo": {
                "id": mechant.id,
                'username': mechant.username,
                "password": mechant.pwd,
                'mobile': mechant.mobile,
                "portrait_img": mechant.portrait_img,
                'min_price': mechant.min_price,
            }
        }
        return Response(data)

    def update(self, request,pk, *args, **kwargs):
            # uid = request.data.get('uid')
        try:
            portrait_img = request.data.get("portrait_img")
            username = request.data.get("username")
            password = request.data.get("password")
            mobile = request.data.get("mobile")
            mer = Merchant.objects.filter(id=pk)
            print('mer',mer)
            if portrait_img:
                mer.update(portrait_img=portrait_img)
            if username:
                mer.update(username=username)
            if password:
                mer.update(pwd=password)
            if mobile:
                mer.update(mobile=mobile)
            return Response({
                "code": 200,
                "msg": "用户修改成功！",
            })
        except Exception as e:
            print('错误>>', e)
            return Response({"code":500, "msg":"服务器错误！"})


# 菜品分类的管理
class DishesClassifyViewSet(ModelViewSet):
    queryset = DishesClassify.objects.all()
    serializer_class = DishesClassifySer
    def create(self, request, *args, **kwargs):
        try:
            uid = request.data.get('uid')
            dish_class_name = request.data.get('dishes_class_name')
            print('uid>>', uid)
            print("dis_name>", dish_class_name)
            djsh = DishesClassify.objects.filter(dishes_class_name=dish_class_name).filter()
            if djsh:
                return Response({
                    'code':204,
                    'msg': "菜品存在"
                })
            DishesClassify.objects.create(dishes_class_name=dish_class_name,merchant_id_id=uid)
            return Response({
                'code': 200,
                "msg": "添加成功！"
            })
        except Exception as e:
            print("错误>>", e)
            return Response({
                "code": 200,
                "msg": "服务器错误！"
            })

    # 获取商家下的菜品
    def list(self, request, *args, **kwargs):
        try:
            cid = request.query_params.get('cid')
            dishes_list = DishesClassify.objects.filter(merchant_id_id=cid).all()
            dishes_ser = DishesClassifySer(dishes_list, many=True)
            mid = Merchant.objects.filter(id=cid).first()
            return Response({
                "code": 200,
                'msg': "获取指定商家下的菜品成功！",
                "data": dishes_ser.data,
                "mer_img": mid.portrait_img
            })


        except Exception as e:
            print('错误>>>', e)
            return Response({
                "code": 500,
                "msg": "服务器错误！"
            })

# 顾客注册
class UserRegister(APIView):
    def post(self, request):
        try:
            account = request.data.get('username')
            password = request.data.get('password')
            mobile = request.data.get('mobile')

            if not all([password,account,mobile]):
                return Response({'code':204, 'message':'用户信息不完整'})

            user = User.objects.filter(username=account).first()

            if user:
                return Response({
                    "code": 204,
                    "msg":"此用户已被注册！"
                })

            pho = User.objects.filter(mobile=mobile).first()

            if pho:
                return Response({
                    "code": 204,
                    "msg": "此手机号已被注册！"
                })
            hash_pwd = generate_password_hash(password)
            User.objects.create(username=account,password=hash_pwd,mobile=mobile)
            return Response({'code':200, 'message':'注册成功'})
        except Exception as e:
            print('错误>>>>', e)
            return Response({"code":500, "message":'服务器出错了'})


# 顾客登录
class UserLoginAPIView(APIView):
    def post(self, request):
        username = request.data.get('username')
        pwd = request.data.get("password")
        mobile = request.data.get("mobile")
        sms_code = request.data.get("sms_code")
        print('username>>', username)
        print('pwd',pwd)

        try:
            user = User.objects.filter(username=username).first()
            if not user:
                return Response({
                    "code": 400,
                    "msg": "没有此用户"
                })

            code_key = "sms_%s"%mobile

            redis_conn = redis.Redis(host='localhost', port=6379, password='123', db=3)
            # 验证验证码
            sms = redis_conn.get(code_key)
            # print('sms', sms)
            if not sms:
                return Response({
                    'code':204,
                    'msg': "验证码过期"
                })
            if sms.decode("utf-8") != sms_code:
                # print('1123')
                return Response({
                    "code": 204,
                    'msg': "验证码错误"
                })

            # pwdd = User.objects.filter(password=pwd).first()
            print('111')
            if check_password_hash(user.password,pwd):
                token = self.gen_token(user)
                # user.last_login = datetime.datetime.now()
                # user.save()
                return Response({
                    'code': 200,
                    'msg': "登录成功",
                    'username': user.username,
                    'id': user.id,
                    'token': token
                })
            else:
                return Response({
                    'code': 204,
                    'msg': "密码错误"
                })
        except Exception as e:
            print('错误', e)
            return Response({
                "code": 500,
                "msg": "服务器错误！"
            })
    @staticmethod
    def gen_token(user):
        # 组织payload数据
        payload = {
            'id':user.id,
            'exp': time.time() + 30000000
        }

        # 使用jwt编码，生成token
        token = jwt.encode(payload=payload, key=settings.SECRET_KEY,algorithm='HS256')
        return token


# 收货地址管理
class AddrViewSet(ModelViewSet):
    queryset = Address.objects.all()
    serializer_class = AddressSer
    lookup_field = "pk"
    lookup_url_kwarg = "pk"
    @check_login
    def list(self, request, *args, **kwargs):
        try:
            uid = request.user
            user_id = uid.id
            addres = Address.objects.filter(user_id=user_id).all()
            if addres:
                addser = AddressSer(addres, many=True)
                return Response({
                    'code': 200,
                    'msg': "获取该用户的收货地址成功",
                    "data": addser.data
                })
            return Response({
                "code": 204,
                "msg": "没有获取到该用户信息！"
            })

        except Exception as e:
            print('错误>>', e)
            return Response({
                'code': 500,
                "msg": "服务器错误！"
            })

    def create(self, request, *args, **kwargs):
        uid = request.data.get('uid')
        address = request.data.get('address')
        print(uid,address)
        try:
            Address.objects.create(user_id_id=uid,address=address)
            return Response({
                "code": 200,
                'msg': "添加收货地址成功！"
            })
        except Exception as e:
            print('错误>>', e)
            return Response({
                'code': 500,
                "msg": "服务器错误"
            })


# 优惠券的管理
class CouponSet(ModelViewSet):
    queryset = Coupon.objects.all()
    serializer_class = CouponSer


# 获取商家下的菜品
class MerchantDishesClass(APIView):
    @merchant_login
    def get(self, request):
        mid = request.user
        print('mid>>', mid)
        dishes_class = DishesClassify.objects.filter(merchant_id=mid).all()
        dishes_ser = DishesClassifySer(dishes_class, many=True)
        if dishes_class:
            return Response({
                "code": 200,
                "msg": "获取菜品成功",
                "data": dishes_ser.data
            })
        else:
            return Response({
                'code': 204,
                'msg': "获取不到该商家的菜品信息"
            })


# 获取菜品分类下的菜
class DishesAPIView(APIView):
    def get(self, request,id):
        # did  = request.data.get('did')
        dis_data = Dishes.objects.filter(dis_class_id=id).all()
        dis_ser = DishesSer(dis_data, many=True)
        if dis_data:
            return Response({
                "code": 200,
                'msg': "获取菜品成功",
                "data": dis_ser.data
            })
        else:
            return Response({
                "code": 204,
                "msg": "没有找到该菜品分类下的菜"
            })


# 菜品管理
class DishesModelSet(ModelViewSet):
    queryset = Dishes.objects.all()
    serializer_class = DishesSer
    def create(self, request, *args, **kwargs):
        try:
            mid = request.data.get('uid')
            dishes_class_id = request.data.get('dishes_class_id')
            dishes_name = request.data.get("dishes_name")
            dishes_price = request.data.get('dishes_price')
            dishes_img = request.data.get('dishes_img')
            dish = Dishes.objects.filter(dishes_name=dishes_name).first()
            if dish:
                return Response({
                    'code': 204,
                    'msg': "商品已经存在！"
                })
            Dishes.objects.create(dishes_name=dishes_name,dishes_price=dishes_price,dishes_img=dishes_img,dis_class_id_id=dishes_class_id,merchant_id_id=mid)
            return Response({
                "code": 200,
                "msg": "添加商品成功！"
            })

        except Exception as e:
            print('错误>>>', e)
            return Response({
                'code': 500,
                "msg": "服务器错误！"
            })


# 管理顾客
class UserInfoAPIView(ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSer

    def update(self, request,pk, *args, **kwargs):
        try:
            # uid = request.data.get('uid')
            portrait_img = request.data.get("portrait_img")
            username = request.data.get("username")
            account = request.data.get("account")
            password = request.data.get("password")
            mobile = request.data.get("mobile")
            sex = request.data.get("sex")
            print('sex', sex)
            age = request.data.get("age")
            uer = User.objects.filter(id=pk)
            print('uer',uer)
            if portrait_img:
                uer.update(portrait_img=portrait_img)
            if username:
                uer.update(username=username)
            if account:
                uer.update(account=account)
            if password:
                pwd = generate_password_hash(password)
                uer.update(password=pwd)
            if mobile:
                uer.update(mobile=mobile)
            if sex:
                uer.update(sex=sex)
            if age:
                uer.update(age=age)
            return Response({
                "code": 200,
                "msg": "用户修改成功！",
            })
        except Exception as e:
            print('错误>>', e)
            return Response({"code":500, "msg":"服务器错误！"})



# 查询已登录的用户
class UserList(APIView):
    @check_login
    def get(self, request):
        user_id = request.user
        user = User.objects.filter(username=user_id).first()

        data={
            "code": 200,
            "msg": "ok",
            "userinfo":{
                "id": user.id,
                'username': user.username,
                "password": user.password,
                'mobile': user.mobile,
                "portrait_img": user.portrait_img,
                'sex': user.sex,
                'age': user.age,
                'account': user.account
            }
        }
        return Response(data)

# 查询已登录的商家
class Merchant_list(APIView):
    @merchant_login
    def get(self, request):
        user_id = request.user
        user = User.objects.filter(username=user_id).first()

        data={
            "code": 200,
            "msg": "ok",
            "userinfo":{
                "id": user.id,
                'username': user.username,
                "password": user.password,
                'mobile': user.mobile,
                "portrait_img": user.portrait_img,
                'sex': user.sex,
                'age': user.age
            }
        }
        print("123>>>>>>",data.get('userinfo.mobile'))
        print("",data.userinfo.mobile)
        print('', data['userinfo']['mobile'])
        return Response(data)


# 获取七牛云token
class QiNiuToken(APIView):
    def get(self, request):
        name = 'p9qiniu' #  空间名
        # access_key 与  secret_key  是七牛云的密钥
        auth = Auth(access_key='L4KBaBkhV52xMvErYgE6XbYDh57uy2qey2qppzRe',
                    secret_key='bildAzQKbSmdtnoAe-dUNjeqM7JMqCWaoURqbaCz')
        token = auth.upload_token(name)
        return Response({"token":token})


# 获取所有店铺
class MersheInfo(APIView):
    def get(self, request):
        mer = Merchant.objects.all()
        mer_ser = MerchantSer(mer, many=True)
        return Response({
            "data": mer_ser.data
        })